package ar.uba.fi.tp2Unit.displayers.gui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.swing.JComponent;

/**
 * It is used to show a pie chart with different results.
 * Each result belongs with a color to differentiate itself
 * from the others.
 * 
 * @author grupo12
 * @see {@link Slice}
 */
@SuppressWarnings("serial")
public class PieChart extends JComponent {

	List<Slice> slices;
	Rectangle area;

	public PieChart(Map<Color, Integer> slices, int width, int height) {
		this.slices = new ArrayList<Slice>();
		Double total = getTotalValue(slices);
		for (Color color : slices.keySet()) {
			this.slices.add(new Slice(slices.get(color) / total * 100, color));
		}
		area = new Rectangle(width, height);
	}

	private Double getTotalValue(Map<Color, Integer> slices) {
		Double total = 0d;
		for (Integer value : slices.values()) {
			total += value;
		}
		return total;
	}

	public void paint(Graphics pieGraphic) {
		drawPie((Graphics2D) pieGraphic);
	}

	void drawPie(Graphics2D pieGraphic) {
		double total = 0.0D;
		for (Slice slice : slices) {
			total += slice.getPercentage();
		}

		double currentPercentageValue = 0.0D;
		for (Slice slice : slices) {
			currentPercentageValue = drawNextSlice(pieGraphic, total,
					currentPercentageValue, slice);
		}
	}

	private double drawNextSlice(Graphics2D pieGraphic, double total,
			double currentPercentageValue, Slice slice) {
		int startAngle = (int) (currentPercentageValue * 360 / total);
		int arcAngle = (int) (slice.getPercentage() * 360 / total);
		pieGraphic.setColor(slice.getColor());
		pieGraphic.fillArc(area.x, area.y, area.width, area.height, startAngle,
				arcAngle);
		currentPercentageValue += slice.getPercentage();
		return currentPercentageValue;
	}

}
